package com.zzyl.nursing.util;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 身份证工具类
 */
public class IDCardUtils {

    /**
     * 通过身份证号获取年龄
     * @param idCard 身份证号
     * @return 年龄
     */
    public static Integer getAgeByIdCard(String idCard) {
        if (idCard == null || idCard.length() < 14) {
            return null;
        }

        String birthDateStr = "";
        if (idCard.length() == 18) {
            birthDateStr = idCard.substring(6, 14);
        } else if (idCard.length() == 15) {
            birthDateStr = "19" + idCard.substring(6, 12);
        }

        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            LocalDate birthDate = LocalDate.parse(birthDateStr, formatter);
            return LocalDate.now().getYear() - birthDate.getYear();
        } catch (Exception e) {
            return null;
        }
    }
}
